<?php

(defined('BASEPATH')) OR exit('No direct script access allowed');

class Ticket_Admin extends Admin_Controller {

    function __construct() {

        parent::__construct();

        $this->load->model('ticket/ticket_model');
        $this->load->model('ticket/ticket_cat_model');
        $this->load->model('ticket/tag_model');
        $this->load->model('ticket/ticket_tag_model');
        $this->load->model('image/image_model');
//        $this->load->helper('currency_helper');
    }

    function list_ticket() {
        $view_data = array();
        $options = $this->_get_search_form_data();

        $this->load->library('pagination');

        $config['base_url'] = site_url('ticket-admin/list-ticket');
        $config['total_rows'] = $this->ticket_model->get_ticket_count($options);
        $config = array_merge($config, get_pagination_config());

        $this->pagination->initialize($config);

        $options['limit'] = $config['per_page'];
        $options['offset'] = $this->uri->segment(3);
        if (!isset($options['offset']) || !is_numeric($options['offset']) || (int) $options['offset'] < 0 || $options['offset'] > $config['total_rows'])
            $options['offset'] = 0;

        $this->_data = $options;
        $this->_data['tickets'] = $this->ticket_model->get_ticket($options);
        $this->_data['category'] = $this->ticket_cat_model->get_categories_array();
        $this->_data['image'] = $this->image_model->get_image_array();

        $this->_data['pagination'] = $this->pagination->create_links();
        $this->display_admin('admin/list');
    }

    private function _get_search_form_data() {

        $options = array();

        if ($this->input->post('btnSubmit') === __('submit')) {

            $cat_id = $this->input->post('cat_id');
            $search = trim(mysql_escape_string($this->input->post('search')));

            if ($cat_id != -1)
                $options['cat_id'] = $cat_id;


            if ($search != NULL && $search != trim(' '))
                $options['search'] = $search;

            $this->phpsession->save('filter', $options);
        }

        $search_session = $this->phpsession->get('filter');

        $options['cat_id'] = isset($search_session['cat_id']) ? $search_session['cat_id'] : -1;
        $options['search'] = (isset($search_session['search'])) ? $search_session['search'] : NULL;

        $options['cat_combo'] = $this->ticket_cat_model->get_categories_combo(
                array(
                    'combo_name' => 'cat_id',
                    'cat_id' => (isset($search_session['cat_id'])) ? $search_session['cat_id'] : -1));


        return $options;
    }

    public function create_ticket() {
        if (isset($_POST['btnSubmit'])) {
            if ($this->_do_validate()) {
                $expiry_date = ($this->input->post('expiry_date')) ? date('Y-m-d', strtotime($this->input->post('expiry_date'))) : NULL;
                $ticket_data = array(
                    'ticket_name' => trim($this->input->post('ticket_name')),
                    'description' => trim($this->input->post('description')),
                    'expiry_date' => $expiry_date,
                    'price' => trim($this->input->post('price')),
                    //'img_id' => $return_value,
                    'quantity' => trim($this->input->post('quantity')),
                    'cat_id' => $this->input->post('cat_id')
                );
                $ticket_id = $this->ticket_model->create_ticket($ticket_data);
                redirect('ticket-admin');
            } else {
                $this->_data['errors'] = validation_errors();
                $view_data = $this->_get_create_form_data();
                $this->_data = $view_data;
                $this->display_admin('ticket/create_ticket');
            }
        } else {
            $view_data = $this->_get_create_form_data();
            $this->_data = $view_data;
            $this->display_admin('ticket/create_ticket');
        }
    }

    private function _get_create_form_data() {
        $view_data = array();
        $view_data['cat_combo'] = $this->ticket_cat_model->get_categories_combo(
                array(
                    'combo_name' => 'cat_id',
                    'cat_id' => (isset($_POST['cat_id'])) ? $this->input->post('cat_id') : 1));
        return $view_data;
    }

    private function _do_validate() {
        $this->form_validation->set_rules('ticket_name', __('ticket_name'), 'trim|required|max_length[300]|xss_clean');
        $this->form_validation->set_rules('price', __('ticket_price'), 'trim|required|greater_than[-1]|xss_clean');
        $this->form_validation->set_rules('quantity', __('ticket_quantity'), 'trim|required|is_natural|xss_clean');
        $this->form_validation->set_rules('cat_id', __('ticket_cat'), 'is_not_default_combo');
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        if (!$this->form_validation->run())
            return FALSE;
        return TRUE;
    }

    /**
     *
     * @param type $options
     * @return type 
     */
    private function _add_tags_for_ticket($options = array()) {

//        $this->load->helper('ticket/ticket_helper');
        $tags = split_tags($options['tags']);
        //Nếu không nhập tags
        if ($tags == '' || $tags == NULL)
            return;

        foreach ($tags as $word) {
            //Kiểm tra đã có tag này trong bảng tags chưa ?
            //Nếu đã có thì lấy ID, nếu chưa có thì insert và lấy ID vừa insert
            $tag = $this->tag_model->get_tag(array('tag_name' => $word));

            if (count($tag) == 0)
                $tag_id = $this->tag_model->add_tag(array('tag_name' => trim($word)));
            else
                $tag_id = $tag[0]->id;

            $ticket_tag = $this->ticket_tag_model->get_ticket_tag(array('ticket_id' => $options['ticket_id'], 'tag_name' => $word));

            if (count($ticket_tag) == 0)
                $this->ticket_tag_model->add_ticket_tag(array('ticket_id' => $options['ticket_id'], 'tag_id' => $tag_id));
        }
    }

    /**
     * 
     */
    function delete_ticket() {
        $ticket_id = $this->input->post('ticket_id');

        $ticket = $this->ticket_model->get_ticket(array('id' => $ticket_id));

        if (count($ticket) == 1) {

            $this->ticket_tag_model->delete_ticket_tag(array('ticket_id' => $ticket_id));
            $this->_delete_junk_tags();

            //TODO: DELETE INVOICE DETAIL
            $this->load->model('invoice/invoice_detail_model');
            $this->invoice_detail_model->delete_invoice_detail(array('ticket_id' => $ticket_id));

            //Delete image:
            if (!is_null($ticket[0]->img_id) && $ticket[0]->img_id > 0)
                modules::run('image/delete_image', array('folder_name' => MODULE_NAME, 'img_id' => $ticket[0]->img_id));

            $this->ticket_model->delete_ticket(array('ticket_id' => $ticket_id));
        }
        redirect('ticket-admin');
    }

    /**
     * 
     */
    private function _delete_junk_tags() {

        $tickets_tags = $this->ticket_tag_model->get_ticket_tag_array();
        $current_tags = $this->tag_model->get_tag();

        foreach ($current_tags as $tag) {
            if (!isset($tickets_tags[$tag->id]))
                $this->tag_model->delelte_tag(array('id' => $tag->id));
        }
    }

    public function edit_ticket() {
        // không cho phép gọi trực tiếp từ url
        if (!$this->is_postback())
            redirect('ticket-admin');

        $view_data = array();
        $options = array();

        if ($this->is_postback() && !$this->input->post('IS_FROM_LIST')) {

            if (!$this->_do_edit_ticket()) {

                $options['error'] = validation_errors();
                $options['tab_index'] = 0;
            }

            if (!is_null($this->__last_message)) {

                $options['error'] = '<div class="error">' . $this->__last_message . '</div>';
                $options['tab_index'] = 1;
            }
        }

        $view_data = $this->_get_edit_form_data();

        $view_data['messages'] = (isset($options['error'])) ? $options['error'] : NULL;
        $view_data['tab_index'] = (isset($options['tab_index'])) ? $options['tab_index'] : 0;


        $this->load->view('ticket/edit_ticket', $view_data);
    }

    //TODO:
    private $_current_img = NULL;

    private function _get_edit_form_data() {
        $view_data = array();

        $ticket_id = $this->input->post('ticket_id');

        // Get from DB
        if ($this->input->post('IS_FROM_LIST')) {
            $ticket = $this->ticket_model->get_ticket(array('id' => $ticket_id));
            $cat_id = $ticket[0]->cat_id;
            $ticket_name = $ticket[0]->ticket_name;
            $description = $ticket[0]->description;
            $expiry_date = $ticket[0]->expiry_date;
            $price = $ticket[0]->price;
            $quantity = $ticket[0]->quantity;

            if ($ticket[0]->img_id != NULL && $ticket[0]->img_id > 0) {
                $image = $this->image_model->get_image_array();
                $this->_current_img = (isset($image[$ticket[0]->img_id])) ? $image[$ticket[0]->img_id] : NULL;
            }

            $tags = join_tags($ticket_id);
        }
        // Get from submit
        else {
            $cat_id = $this->input->post('cat_id');
            $ticket_name = $this->input->post('ticket_name');
            $description = $this->input->post('description');
            $expiry_date = $this->input->post('expiry_date');
            $price = $this->input->post('price');
            $quantity = $this->input->post('quantity');
            $tags = $this->input->post('tags');
        }

        $view_data['ticket_id'] = $ticket_id;
        $view_data['cat_combo'] = $this->ticket_cat_model->get_categories_combo(
                array('combo_name' => 'cat_id', 'cat_id' => $cat_id)
        );

        $view_data['ticket_name'] = $ticket_name;
        $view_data['description'] = $description;
        $view_data['expiry_date'] = $expiry_date;
        $view_data['price'] = $price;
        $view_data['quantity'] = $quantity;
        $view_data['current_img'] = $this->_current_img;
        $view_data['tags'] = $tags;

        return $view_data;
    }

    private function _do_edit_ticket() {

        if ($this->_do_validate()) {

            $ticket_id = $this->input->post('ticket_id');

            $ticket = $this->ticket_model->get_ticket(array('id' => $ticket_id));

            $expiry_date = ($this->input->post('expiry_date')) ? date('Y-m-d', strtotime($this->input->post('expiry_date'))) : NULL;

            $img_id = NULL;

            if ($_FILES['userfile']['name'] != '') {

                if ($ticket[0]->img_id != NULL && $ticket[0]->img_id > 0) {

                    modules::run('image/delete_image', array('folder_name' => MODULE_NAME, 'img_id' => $ticket[0]->img_id));
                }

                $img_id = modules::run('image/upload_image', array('folder_name' => MODULE_NAME, 'thumbnail' => TRUE));

                if ($img_id != NULL && !is_numeric($img_id)) {

                    $this->__last_message = $img_id;

                    return FALSE;
                }
                $this->__last_message = NULL;
            }

            $ticket_data = array(
                'id' => $ticket_id,
                'ticket_name' => $this->input->post('ticket_name'),
                'description' => $this->input->post('description'),
                'expiry_date' => $expiry_date,
                'price' => $this->input->post('price'),
                'img_id' => $img_id,
                'quantity' => $this->input->post('quantity'),
                'cat_id' => $this->input->post('cat_id')
            );

            $this->ticket_model->update_ticket($ticket_data);
            redirect('ticket-admin');
        } else {
            return FALSE;
        }
    }

}
